#!/usr/bin/env python
import serial
import sys
import pty
import os
import time
import select
from time import ctime
from time import sleep

class SerialPortServer(object):
    master_ = None
    slave_ = None
    slaveName_ = None
    serial_ = None

    def __init__(self, baudrate=115200):
        assert isinstance(baudrate,int),"'port' must be a integer."
        # Create a pty
        self.master_,self.slave_ = pty.openpty()
        self.slaveName_ = os.ttyname(self.slave_)
        print "slave device names:", self.slaveName_
        # Open pty
        print " Open the port to "+self.slaveName_
        sleep(1) 
        self.serial_=serial.Serial(self.slaveName_,baudrate,timeout=0.5) #pass parameter:slaveName
        print "Open port successful! the port information:"
        print self.serial_
        print "\n"

    def getSlaveName(self):
        return self.slaveName_

    def isOpen(self):
        return self.serial_.isOpen()

    def send(self,msg):
        msg = msg + "\r\n"
        ret = os.write(self.master_, msg)
        sys.stdout.flush()  #flush the buffer
        return ret

    def recv(self):
        return os.read(self.master_,1024)

    def close(self):
        os.close(self.master_)
        os.close(self.slave_)
        self.master_ = None
        self.slave_ = None

